import { createContext, useState, useEffect } from "react";
import { setGlobalSetUserInfo } from "@/utils/request";
import { getStorage } from "@/utils/storage";
import Taro from "@tarojs/taro";

interface LoginContextType {
  userInfo: any;
  setUserInfo: (userInfo: any) => void;
}

export const LoginContext = createContext<LoginContextType>({
  userInfo: null,
  setUserInfo: () => {},
});

const LoginProvider = ({ children }: { children: React.ReactNode }) => {
  const [userInfo, setUserInfo] = useState(null);
  useEffect(() => {
    const userInfo = getStorage("userInfo");
    if (userInfo) {
      setUserInfo(userInfo);
    }
    const updateManager = Taro.getUpdateManager();
    updateManager.onUpdateReady(function () {
      Taro.showModal({
        title: "更新提示",
        content: "新版本已经准备好，是否重启应用？",
        success(res) {
          if (res.confirm) {
            updateManager.applyUpdate();
          }
        },
      });
    });
    setGlobalSetUserInfo(setUserInfo);
  }, []);
  return (
    <LoginContext.Provider
      value={{
        userInfo,
        setUserInfo,
      }}
    >
      {children}
    </LoginContext.Provider>
  );
};

export default LoginProvider;
